/*
 * @(#)MaintFormElementAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.web;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.form.FormConstant;
import com.dcivision.form.FormErrorConstant;
import com.dcivision.form.bean.FormAttach;
import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormPage;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSection;
import com.dcivision.form.bean.FormSelectionField;
import com.dcivision.form.bean.FormSelectionFieldOption;
import com.dcivision.form.bean.FormSubmissionHtml;
import com.dcivision.form.bean.MtmFormDynamicValue;
import com.dcivision.form.bean.MtmFormSectionFormElement;
import com.dcivision.form.dao.FormAttachDAObject;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.form.dao.FormPageDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.form.dao.FormSelectionFieldDAObject;
import com.dcivision.form.dao.FormSelectionFieldOptionDAObject;
import com.dcivision.form.dao.FormSubmissionHtmlDAObject;
import com.dcivision.form.dao.FormValidationRuleDAObject;
import com.dcivision.form.dao.MtmFormDynamicValueDAObject;
import com.dcivision.form.dao.MtmFormSectionFormElementDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.framework.web.WebUtil;

/**
  MaintFormElementAction.java

  This class is for maint form element.

    @author          Jamin Wang
    @company         DCIVision Limited
    @creation date   18/1/2004
    @version         $Revision: 1.99.2.5 $
*/

public class MaintFormElementAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.99.2.5 $";

  protected String listName = "";

  public MaintFormElementAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.form.dao.FormElementDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.FORM_SETUP);
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;
    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
    if (request.getParameter("formPageID")!=null){
        request.setAttribute("formPageID",request.getParameter("formPageID"));
    }

    if (request.getParameter("formRecordID")!=null
        && !"null".equals(request.getParameter("formRecordID"))){
       request.setAttribute("formRecordID",request.getParameter("formRecordID"));
    }
    if (request.getParameter("formSubmissionID")!=null){
        request.setAttribute("formSubmissionID",request.getParameter("formSubmissionID"));
    }
   //get conditionIDs for dynamic value to select sql condition.
     FormRecordDAObject formRecordDAObject = new FormRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
     if(request.getSession().getAttribute("formRecordID")!=null
         && !"null".equals(request.getSession().getAttribute("formRecordID"))){
         Integer formRecordID =  new Integer(request.getSession().getAttribute("formRecordID").toString());
         log.debug("formRecordID=" +formRecordID);
         ArrayList list = (ArrayList)formRecordDAObject.getSearchElementListByFormRecordID(formRecordID);
         ArrayList conditionIDs = new ArrayList();
         FormElement element;
         log.debug("list.size="+ list.size());
         for(int i=0;i<list.size();i++){
             element=(FormElement)list.get(i);
             log.debug("elementID="+ element.getID() +" :  elemenType ="+element.getElementType());
             if(element!=null && element.getElementType().equals(FormElementType.ELEMENT_CONDITIONAL_FIELD)){
                 conditionIDs.add(new org.apache.struts.util.LabelValueBean(element.getFieldName(),element.getID().toString()));
                 log.debug("elementID="+ element.getID());
            }
         }
         request.setAttribute(FormConstant.FORM_DB_LOOKUP_CONDITIONID_COLLECTION,conditionIDs);
         request.setAttribute(FormConstant.FORM_DB_LOOKUP_OPREATORS_COLLECTION,FormConstant.OPERATORS);
      }
  //get conditionIds end

   // begin get validation rule
   FormValidationRuleDAObject formValidationRuleDAO = new FormValidationRuleDAObject(this.getSessionContainer(request), this.getConnection(request));
   List validationRuleList = formValidationRuleDAO.getFullList();
   request.setAttribute("validationRuleList",validationRuleList);
   //end get validation rule

   if ("I".equals((navMode))) {
    //  Set the function code for current action.
        ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
        if (forward!=null) {
          return forward;
        }
      if (maintForm.getID()!=null) {
        try{
            createRecord(maintForm,"html",request);
            this.commit(request);
        }catch(ApplicationException appEx) {
            this.handleApplicationException(request,appEx);
          log.error(appEx.getMsgCode());
        }
       }
       return mapping.findForward("I");
   } else  if ("ED".equals((navMode))) {
      return mapping.findForward("ED");
   } else if (GlobalConstant.OP_MODE_REFRESH.equals(opMode)) {
      // Set the function code for current action.

      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
      refreshFormData(mapping, maintForm, request, response);
      // falcon_add_start
      if(!Utility.isEmpty(request.getParameter("SelectV"))){
        if ("I".equals(request.getParameter("SelectV"))){
          return mapping.findForward("IMG");
       }
      }
      // falcon_add_end
      return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
   } else {
      if (GlobalConstant.OP_MODE_DELETE.equals(opMode)) {
        request.setAttribute("formRecordID",request.getParameter("formRecordID"));
        request.setAttribute("formSectionID",request.getParameter("formSectionID"));
      }
      // falcon_add_start
      if(!Utility.isEmpty(request.getParameter("SelectV"))){
        if ("I".equals(request.getParameter("SelectV"))){
          super.execute(mapping, form, request, response);
          return mapping.findForward("IMG");
       }
      }
      // falcon_add_end
     return super.execute(mapping, form, request, response);
   }

  }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form,HttpServletRequest request, HttpServletResponse response) throws ApplicationException {

    MaintFormElementForm formElementForm=(MaintFormElementForm)form;
    String navMode = (formElementForm!=null) ? formElementForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
    if (!"I".equals((navMode))) {
      if (!FormElementType.isAttachment(formElementForm.getElementType())){
       if(FormElementType.ELEMENT_CHECK_BOX.equals(formElementForm.getElementType())) {
          String[] defaultValueArray=null;
         if (request.getParameter("defaultValue")!=null){
          defaultValueArray = request.getParameterValues("defaultValue");
         }

         String defaultValue = "";
       if (defaultValueArray!=null){
         for (int i = 0; i < defaultValueArray.length; i++) {
           defaultValue += defaultValueArray[i] + ",";
         }
       }
         formElementForm.setDefaultValue(defaultValue);
       }else{
         formElementForm.setDefaultValue(request.getParameter("defaultValue"));
       }
      }
     FormElementDAObject formElementDAObject=new FormElementDAObject(this.getSessionContainer(request), this.getConnection(request));

     String fontStyle="";
     if (request.getParameter("fontStyleBold") != null) {
      fontStyle += "B";
    }
     if (request.getParameter("fontStyleUnderline") != null) {
      fontStyle += "U";
    }
     if (request.getParameter("fontStyleItalic") != null) {
      fontStyle += "I";
    }
     formElementForm.setFontStyle(fontStyle);

     if (request.getParameter("requiredFlag")!=null) {
         formElementForm.setRequiredFlag("Y");
     } else {
      formElementForm.setRequiredFlag("N");
    }

     formElementForm.setIsLabel("N");
     if (FormElementType.isSelection(formElementForm.getElementType())) {
       FormSelectionFieldDAObject FormSelectionFieldDAObject = new
           FormSelectionFieldDAObject(this.getSessionContainer(request),
                                      this.getConnection(request));
       FormSelectionField tmpFormSelectionField = new FormSelectionField();
       FormSelectionField formSelectionField = null;

       try {
         tmpFormSelectionField = (FormSelectionField)FormSelectionFieldDAObject.getByElementID(new Integer(formElementDAObject.getNexID()));
         tmpFormSelectionField.setDisplayType(formElementForm.getDisplayType());
         formSelectionField = (FormSelectionField) FormSelectionFieldDAObject.
             updateObject(tmpFormSelectionField);
       } catch (ApplicationException ae) {
         if (ae.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)) {
           tmpFormSelectionField.setElementID(new Integer(formElementDAObject.getNexID()));
           tmpFormSelectionField.setDisplayType(formElementForm.getDisplayType());
           formSelectionField = (FormSelectionField)
               FormSelectionFieldDAObject.insertObject(tmpFormSelectionField);
         }
       }
       //set mtm Form data
       formElementForm.setDisplayType(formSelectionField.getDisplayType());

       //set form selection field option
       FormSelectionFieldOptionDAObject FormSelectionFieldOptionDAObject = new
           FormSelectionFieldOptionDAObject(this.getSessionContainer(request),
                                            this.getConnection(request));
       FormSelectionFieldOption tmpFormSelectionFieldOption = new
           FormSelectionFieldOption();
       FormSelectionFieldOption formSelectionFieldOption = null;

       try {
         tmpFormSelectionFieldOption = (FormSelectionFieldOption)
             FormSelectionFieldOptionDAObject.getBySelectionFieldID(
             formSelectionField.getID());
         FormSelectionFieldOptionDAObject.deleteListBySelectionFieldID(
             formSelectionField.getID());

       } catch (ApplicationException ae) {
         if (ae.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)) {

         }
       }
       for (int i = 0; i >= 0 && i < formElementForm.getOptionList().size(); i++) {
         tmpFormSelectionFieldOption = formElementForm.getOption(i);
         tmpFormSelectionFieldOption.setSelectionFieldID(formSelectionField.
             getID());
         formSelectionFieldOption = (FormSelectionFieldOption)
             FormSelectionFieldOptionDAObject.insertObject(
             tmpFormSelectionFieldOption);
       }

     }
     if (formElementForm.getElementType().equals(FormElementType.ELEMENT_IMAGE) && formElementForm.getUploadFile() != null){
        formElementForm.setFileName(TextUtility.formatFileName(request.getParameter("trueFileName")));
     }
     super.insertRecord(mapping, formElementForm, request, response);

      //insert record of MTM_FORM_DYNAMICVALUE table begin
      MtmFormDynamicValueDAObject mtmFormDynamicValueDAObject =
        new MtmFormDynamicValueDAObject(this.getSessionContainer(request),this.getConnection(request));
      this.insertMtmDynamicValue(formElementForm,mtmFormDynamicValueDAObject);
      //insert record of MTM_FORM_DYNAMICVALUE table end

      com.dcivision.form.web.MaintFormElementForm maintFormElementForm = (com.dcivision.form.web.MaintFormElementForm)form;

      createRecord(maintFormElementForm,"image",request);
    }else{
        createRecord(formElementForm,"html",request);
    }
  }

  public void createRecord(AbstractActionForm obj,String uploadType, HttpServletRequest request)
      throws ApplicationException {
    try {
      FileOutputStream fos = null;
      com.dcivision.form.web.MaintFormElementForm maintform = (com.dcivision.
          form.web.MaintFormElementForm) obj;
      String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
     if (uploadType.equals("image")){
       if (!Utility.isEmpty(maintform.getFileName()) && maintform.getFileName() != null) {
         //String sType = maintform.getFileName().substring(maintform.getFileName().indexOf("."), maintform.getFileName().length());
       //bill add for EIP-1819
       String sType = maintform.getFileName().substring(maintform.getFileName().lastIndexOf("."), maintform.getFileName().length());
         if (!(".png".equalsIgnoreCase(sType) || ".gif".equalsIgnoreCase(sType) || ".jpg".equalsIgnoreCase(sType) || ".bmp".equalsIgnoreCase(sType) || ".jpeg".equalsIgnoreCase(sType))){
           // Reset the id value except for the operation is update.
           if (!GlobalConstant.OP_MODE_UPDATE.equals(obj.getOpMode())) {
           maintform.setID(null);
           }
           throw new ApplicationException(FormErrorConstant.FORM_INVALID_PICTURE_FORMAT);
        }
        if (maintform.getFileName().indexOf(".") !=-1){
          fos = new FileOutputStream(path + "/" + maintform.getID() + maintform.getFileName().substring(
              maintform.getFileName().indexOf("."), maintform.getFileName().length()));
        }else{
          fos = null;
        }
      }
    }
    InputStream inputStream = null;
      try {
        if (fos != null) {
          if (maintform.getElementType().equals(FormElementType.ELEMENT_IMAGE)) {
              inputStream = maintform.getUploadFile().getInputStream();
            // Check input stream, if it is not null but is empty, throw exception.
            if (!Utility.isEmpty(inputStream) && inputStream.available() <= 0) {
              // Reset the id value except for the operation is update.
              if (!GlobalConstant.OP_MODE_UPDATE.equals(obj.getOpMode())) {
                maintform.setID(null);
              }
              throw new ApplicationException(FormErrorConstant.FORM_UPLOAD_PICTURE_IS_EMPTY_OR_NOT_FOUND);
            }
            int bufferSize = 8192;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            while ( (length = inputStream.read(buffer, 0, bufferSize)) != -1) {
              fos.write(buffer, 0, length);
            }
          }
          fos.flush();
        }
       if (!uploadType.equals("image")){
           if (maintform.getUploadFile().getFileName().indexOf(".")!=-1){
             if ((maintform.getUploadFile().getFileName().substring(maintform.getUploadFile().getFileName().indexOf("."),maintform.getUploadFile().getFileName().length())).toLowerCase().equals(".htm")
                    || (maintform.getUploadFile().getFileName().substring(maintform.getUploadFile().getFileName().indexOf("."),maintform.getUploadFile().getFileName().length())).toLowerCase().equals(".html") ){
              if ("I".equals(maintform.getNavMode())) {
                     if("Y".equals(request.getParameter("formSubmissionHtml"))){
                            try{
                            updateFileToDB(maintform,"html", request);
                            }catch(ApplicationException appEx){
                          throw appEx;
                            }
                     }else{
                         try{
                                uploadFileToDB(maintform,"html", request);
                        }catch(ApplicationException appEx){
                      throw appEx;
                        }
                     }
                     request.setAttribute("Result","Upload file success !");
                     log.info("Upload file success !");
                     addMessage(request, MESSAGE_RECORD_UPDATE);
              }
             }else{
                 log.info("Upload file occur fail because file's format is not htm !");
                 throw new ApplicationException(ErrorConstant.FORM_FILE_FORMATE_IS_NOT_HTML);
             }
           } else{
                log.info("Upload file occur fail because file's format is not htm !");
                throw new ApplicationException(ErrorConstant.FORM_FILE_FORMATE_IS_NOT_HTML);
           }
          }

      } catch(ApplicationException appEx){
        throw appEx;
      }catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.FORM_UPLOAD_FILE_FAIL);
      } finally {
        try {
          if (inputStream != null) {
            inputStream.close();
          }
        } catch (IOException ioe) {}
        try {
          if (fos != null) {
            fos.close();
          }
        } catch (IOException ioe) {}
      }
    } catch (ApplicationException appEx) {
      throw appEx;
    }catch (IOException ioe){
        throw new ApplicationException(DmsErrorConstant.ARCHIVE_ROOT_NOT_EXIST);
    }catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {
    }
  }

  /**
   * <p>
   * Split given input stream into section HTML.
   * A runtime exception <code>NullPointerException</code> will be throws if the given input
   * stream is <code>null</code>.
   *
   * <p>
   * NOTE: You must keep the double identify tag stand by underlying pattern.
   * <pre>
   *       begin: "&lt;!--BEGIN SectionID[0-9]*--&gt;";
   *       end: "&lt;!--END SectionID[0-9]*--&gt;";
   * </pre>
   *
   * @param reader the the source input stream.
   * @return a <code>Map</code> contains the section HTML get from the input
   *         stream <code>reader</code>, an empty <code>Map</code> will be
   *         returned if we cann't find any section HTML from the given input
   *         stream.
   * @throws IOException If an I/O error occurs.
   * @throws NullPointerException If the given parameter <code>reader</code> is <code>null</code>.
   */
  private Map getSectionHTMLFromInputStream(BufferedReader reader)
      throws IOException {

    if (reader == null) {
      throw new NullPointerException("Input steam is null!");
    }

    Map sectionHTMLMap = new TreeMap();

    String line = null;
    String sectionID = null;
    StringBuffer sectionContent = null;

    // Split input stream into form-section block.
    // Split tag must be underlying pattern.
    // begin: "<!--BEGIN SectionID[0-9]*-->"
    // end: "<!--END SectionID[0-9]*-->"
    while ((line = reader.readLine()) != null) {

      // Anchor the begin position to search fo this line.
      int searchBeginIndex = 0;

      while (true) {

        // Function for search the beigin-tag.
        if (sectionID == null) {

          // Anchor the begin-tag's begin index of this line.
          int anchorBeginIndex = line.indexOf("<!--BEGIN SectionID",
              searchBeginIndex);

          // Break parsing this line if section hasn't begin and any begin
          // tag is found.
          if (anchorBeginIndex < 0) {
            break;
          }

          // If a begin-tag is found, anchor the "sectionID", re-init the
          // "searchBeginIndex" and "sectionContent" for further parsing.
          if (anchorBeginIndex > -1) {
            sectionID = line.substring(anchorBeginIndex
                + "<!--BEGIN SectionID".length(), line.indexOf("-->",
                anchorBeginIndex));
            searchBeginIndex = line.indexOf("-->", anchorBeginIndex)
                + "-->".length();
            sectionContent = new StringBuffer();
          }
        }

        // Function for existed begin-tag anchor.
        if (sectionID != null) {

          // Anchor the end tag's begin index of this line.
          int anchorEndIndex = line
              .indexOf("<!--END SectionID", searchBeginIndex);

          // Append the content for the existed section.
          if (anchorEndIndex < 0) {
            // If section has begin, there must be an end-tag,
            // otherwise, append all of the content from search index
            // to the end for existed section and break parse for this
            // line.
            sectionContent.append(line.substring(searchBeginIndex) + "\n");
            break;
          }

          // Append the content for the existed section and put the
          // section into a map if an end tag is found.
          // Re-init "sectionID" and "searchBeginIndex" for further
          // parsing.
          if (anchorEndIndex > -1) {
            if (anchorEndIndex > searchBeginIndex) {
              sectionContent.append(line.substring(searchBeginIndex,
                  anchorEndIndex));
            }
            sectionHTMLMap.put("section" + sectionID, sectionContent.toString());
            sectionID = null;
            searchBeginIndex = line.indexOf("-->", anchorEndIndex)
                + "-->".length();
          }
        }

        // Break if reach the end of this line.
        if (searchBeginIndex >= line.length()) {
          break;
        }
      }
    }

    return sectionHTMLMap;
  }

  public void uploadFileToDB(AbstractActionForm obj,String uploadType, HttpServletRequest request)
  throws ApplicationException {
    try{
      MaintFormElementForm maintForm = (MaintFormElementForm) obj;
      if (maintForm.getUploadFile()!= null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(maintForm.getUploadFile().getInputStream(),"UTF-8"));

        // Split section HTML from input stream into a Map for further process.
        Map sectionHTML = this.getSectionHTMLFromInputStream(in);
        /* Commented by Brook.Huang. This section function is extract into method {@link #getSectionHTMLFromInputStream(BufferedReader)}.
        String sDataLine="" ;
        String sectionID = null;
        Map sectionHTML = new TreeMap();
        StringBuffer sb = new StringBuffer();
        while((sDataLine=in.readLine()) != null){
            if(sDataLine.indexOf("<!--BEGIN SectionID")>-1){
                sectionID = sDataLine.substring(sDataLine.indexOf("<!--BEGIN SectionID")+"<!--BEGIN SectionID".length(), sDataLine.indexOf("-->"));
                sb = new StringBuffer();
                continue;
            }
            if(sDataLine.indexOf("<!--END SectionID")>-1){
                sectionHTML.put("section"+sectionID, sb.toString());
                sectionID = null;
                continue;
            }
            if(!Utility.isEmpty(sectionID)){
                sb.append(sDataLine).append("\n");
            }
        }
        sDataLine = null;
        sectionID = null;
        */

        FormSubmissionHtmlDAObject formSubmissionHtmlDAO = new FormSubmissionHtmlDAObject(this.getSessionContainer(request), this.getConnection(request));
        FormPageDAObject formPageDAO = new FormPageDAObject(this.getSessionContainer(request), this.getConnection(request));
        List formPageList = formPageDAO.getDetailListByFormRecordID(new Integer(request.getParameter("formRecordID")));
        for (int pp =0; pp<formPageList.size(); pp++){
          FormPage formPage = (FormPage)formPageList.get(pp);
          List formSectionList = formPage.getFormSectionList();
          for (int i = 0;i < formSectionList.size();i++){
            FormSubmissionHtml formSubmissionHtml = new FormSubmissionHtml();
            formSubmissionHtml.setFormRecordID(new Integer(request.getParameter("formRecordID")));
            formSubmissionHtml.setFormPageID(formPage.getID());
            formSubmissionHtml.setVersion("1");
            FormSection formSection = (FormSection)formSectionList.get(i);
            formSubmissionHtml.setFormSectionID(formSection.getID());

            String sHtml = (String)sectionHTML.get("section"+formSection.getID());
            StringBuffer buffer = new StringBuffer();
            String uploadFileName = maintForm.getUploadFile().toString();
            uploadFileName = uploadFileName.substring(0,uploadFileName.lastIndexOf("."));
            uploadFileName = regexString(uploadFileName);
            Pattern pattern = java.util.regex.Pattern.compile(uploadFileName+"[^\"]*");
            Matcher matcher = pattern.matcher(sHtml);
            while(matcher.find()){
              String imageName = "";
              if (matcher.group(0).indexOf("IconCalendar.gif")>-1){
                imageName = WebUtil.getImage(request, "IconCalendar.gif");
                matcher.appendReplacement(buffer, imageName );
              }else if (matcher.group(0).indexOf("ButtonUploadAttachment.gif")>-1){
                imageName = WebUtil.getImage(request, "ButtonUploadAttachment.gif", false);
                matcher.appendReplacement(buffer, imageName );
              }else if(matcher.group(0).indexOf("IconSearchUser.gif")>-1){
                imageName = WebUtil.getImage(request, "IconSearchUser.gif");
                matcher.appendReplacement(buffer, imageName );
              }else {
                try{
                  String attachID = matcher.group(0).substring(matcher.group(0).indexOf("/")+1,matcher.group(0).length());
                  if(attachID.indexOf(".") != -1){
                    attachID=attachID.substring(0, attachID.indexOf("."));
                  }
                  Integer.parseInt(attachID);
                  FormAttachDAObject formAttachDAObject = new FormAttachDAObject(this.getSessionContainer(request),this.getConnection(request));
                  FormAttach formAttach= (FormAttach)formAttachDAObject.getObjectByID(new Integer(attachID));
                  String attachName = formAttach.getFileName();
                  attachName = attachID + attachName.substring(attachName.indexOf("."),attachName.length());
                  imageName = "../form/ShowFormImageServlet/"+attachName;
                  matcher.appendReplacement(buffer, imageName );
                }catch(Exception es){
                }
              }
            }
            matcher.appendTail(buffer);
            sHtml = buffer.toString();
            Object object = sHtml;
            try{
              formSubmissionHtml.setPageHtml(object);
            }catch (Exception e){
              log.info(ErrorConstant.FORM_IMPORT_HTML_NOT_FOUND_SECTION);
              throw new ApplicationException(ErrorConstant.FORM_IMPORT_HTML_NOT_FOUND_SECTION);
            }
            formSubmissionHtmlDAO.insertObject(formSubmissionHtml);
          }
        }
      }
    }catch (FileNotFoundException e) {
      log.error(e, e);
      throw new ApplicationException(e);
    }catch (IOException e) {
      log.error(e, e);
      throw new ApplicationException(e);
    }
  }

    public void updateFileToDB(AbstractActionForm obj,String uploadType, HttpServletRequest request)
    throws ApplicationException {
        FormSubmissionHtmlDAObject formSubmissionHtmlDAO = new FormSubmissionHtmlDAObject(this.getSessionContainer(request), this.getConnection(request));
        List formSubmissionHtmlList =  formSubmissionHtmlDAO.getListByRecordID(new Integer(request.getParameter("formRecordID")));
        for (int i = 0;i < formSubmissionHtmlList.size();i++){
            FormSubmissionHtml tmpFormSubmissionHtml =(FormSubmissionHtml) formSubmissionHtmlList.get(i);
            formSubmissionHtmlDAO.deleteObject(tmpFormSubmissionHtml);
        }
        uploadFileToDB(obj,uploadType,request);
    }

  public void refreshFormData(ActionMapping mapping, AbstractActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
      throws ApplicationException {
    MaintFormElementForm FormElementForm = (MaintFormElementForm) form;

    // Hold default selected value for multiple element(s) such as 'RADIO' 'CHECK BOX' etc.
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    String[] defaultValueArr = null;
    if (request.getParameter("defaultValue")!= null){
      defaultValueArr = request.getParameterValues("defaultValue");
    }
    if (!Utility.isEmpty(defaultValueArr)) {
      String defaultValues = TextUtility.join(",", defaultValueArr);
      // Type of check box element, append "," at the end of string values for viewer
      // level to display.
      if (FormElementType.ELEMENT_CHECK_BOX.equals(FormElementForm.getElementType())) {
        defaultValues += ",";
      }
      FormElementForm.setDefaultValue(defaultValues);
    }

    try {
      int listSize = 0;
      int intNewField = 0;
      String sqlResult[]=FormElementForm.getSelectedSqlResult();
      List optionList = FormElementForm.getAllOptionList();
      try {
        listSize = TextUtility.parseInteger(request.getParameter("listSize"));
        intNewField = TextUtility.parseInteger(request.getParameter("newField"));
        if(sqlResult==null||sqlResult.length<1){
            log.debug("SelectedSqlResult is empty or null!");
        }else{
            intNewField=sqlResult.length;
            String str = getResources(request).getMessage((Locale)(request.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY)),"contact.label.select");
            for(int i=0;i<sqlResult.length;i++){
                log.debug("The "+i+"th seleted sql result is "+sqlResult[i]);
                if(!sqlResult[i].equals(str)){
              FormSelectionFieldOption option = new FormSelectionFieldOption();
              option.setSequence(new Integer(optionList.size()));
              if(sqlResult[i].indexOf(",")>0){
                option.setLabel(sqlResult[i].substring(0,sqlResult[i].indexOf(",")));
                option.setStartValue(sqlResult[i].substring(sqlResult[i].indexOf(",")+1));
              }else{
                option.setLabel(sqlResult[i]);
              }
              optionList.add(option);
                }
            }
        }
      } catch (Exception e) {
        throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
      }

      int sum = 0;
      sum = listSize + intNewField;

      for (int i = 0; i < TextUtility.parseInteger(request.getParameter("listSize")); i++){
        if("Y".equals(((FormSelectionFieldOption)optionList.get(i)).getIsDelete())){
          sum--;
          listSize--;
        }
      }

      String bold = "";
      String underline = "";
      String italic = "";
      if (FormElementForm.getFontStyleBold() != null) {
        bold = FormElementForm.getFontStyleBold();
      }

      if (FormElementForm.getFontStyleUnderline() != null) {
        underline = FormElementForm.getFontStyleUnderline();
      }

      if (FormElementForm.getFontStyleItalic() != null) {
        italic = FormElementForm.getFontStyleItalic();
      }

      FormElementForm.setFontStyle(bold + underline + italic);

      request.setAttribute("listSize", new Integer(listSize));
      request.setAttribute("newFieldsSize", new Integer(sum));
      request.setAttribute("newField", new Integer(intNewField));

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
    }
  }

  public void selectRecord(ActionMapping mapping,
                           AbstractActionForm form,
                           HttpServletRequest request,
                           HttpServletResponse response)
      throws ApplicationException {
    try {
      MaintFormElementForm FormElementForm = (MaintFormElementForm)form;

      String fieldName = FormElementForm.getFieldName();
      //get form element
      Integer FormElementID = TextUtility.parseIntegerObj(FormElementForm.getID());
      FormElementDAObject formElementDAO = new FormElementDAObject(this.getSessionContainer(request), this.getConnection(request));
      FormElement formElement = (FormElement)formElementDAO.getObjectByID(FormElementID);

      //get MtmFormDynamicValue begin
      MtmFormDynamicValueDAObject mtmFormDynamicValueDAObject =
        new MtmFormDynamicValueDAObject(this.getSessionContainer(request),this.getConnection(request));
      this.getMtmDynamicValue(formElement,mtmFormDynamicValueDAObject);
      //get MtmFormDynamicValue end
      FormElementForm.setFormData(formElement);

      if (request.getParameter("formSectionID")!=null){
        request.setAttribute("formSectionID",request.getParameter("formSectionID").toString());
      }else{
        request.setAttribute("formSectionID",FormElementForm.getID());
      }

      //getfilename
      if (FormElementForm.getElementType()!=null){
        request.setAttribute("formRecordID",request.getParameter("formRecordID"));
        request.setAttribute("formSectionID",request.getParameter("formSectionID"));
        if (FormElementForm.getElementType().equals(FormElementType.ELEMENT_IMAGE)) {
          setFileName(mapping,form,request, response);
        }
      }

      //get form selection field
      if(FormElementType.isSelection(FormElementForm.getElementType())){
        FormSelectionFieldDAObject FormSelectionFieldDAObject = new FormSelectionFieldDAObject(this.getSessionContainer(request), this.getConnection(request));
        FormSelectionField tmpFormSelectionField = new FormSelectionField();

        try{
          tmpFormSelectionField = (FormSelectionField) FormSelectionFieldDAObject.getByElementID(formElement.getID());
        } catch(ApplicationException ae){
          if(ae.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)){
            tmpFormSelectionField.setDisplayType(null);
          }
        }

        FormElementForm.setDisplayType(tmpFormSelectionField.getDisplayType());

        //get form field option
        FormSelectionFieldOptionDAObject FormSelectionFieldOptionDAObject = new FormSelectionFieldOptionDAObject(this.getSessionContainer(request), this.getConnection(request));
        List optionList= new ArrayList();
        try{
          optionList = FormSelectionFieldOptionDAObject.getListBySelectionFieldID(tmpFormSelectionField.getID());
          FormElementForm.setOptionList(optionList);
        }catch(ApplicationException ae){
          if(ae.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)){
          }
        }
      }
     // set the Element Name of FormElement that it is field value in EditFormSectionFormElement.jsp file.
      if(!Utility.isEmpty(fieldName)){
        FormElementForm.setFieldName(fieldName);
      }

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {}
  }

  public void updateRecord(ActionMapping mapping,AbstractActionForm form,
                           HttpServletRequest request,
                           HttpServletResponse response)
      throws ApplicationException {
    try {
      MaintFormElementForm FormElementForm = (MaintFormElementForm) form;
      if (!FormElementType.isAttachment(FormElementForm.getElementType())){

        if (FormElementType.ELEMENT_CHECK_BOX.equals(FormElementForm.getElementType())) {
          String[] defaultValueArray=null;
        if (request.getParameter("defaultValue")!=null){
          defaultValueArray = request.getParameterValues("defaultValue");
        }

        String defaultValue = "";
        if (defaultValueArray!=null){
           for (int i = 0; i < defaultValueArray.length; i++) {
             defaultValue += defaultValueArray[i] + ",";
           }
         }
         FormElementForm.setDefaultValue(defaultValue);
       } else {
         FormElementForm.setDefaultValue(request.getParameter("defaultValue"));
       }
      }
      String fontStyle = "";
      if (request.getParameter("fontStyleBold") != null) {
        fontStyle += "B";
      }
      if (request.getParameter("fontStyleUnderline") != null) {
        fontStyle += "U";
      }
      if (request.getParameter("fontStyleItalic") != null) {
        fontStyle += "I";
      }
      FormElementForm.setFontStyle(fontStyle);

      if (FormElementForm.getRequiredFlag()!=null) {
          FormElementForm.setRequiredFlag("Y");
      } else {
        FormElementForm.setRequiredFlag("N");
      }

      FormElementForm.setIsLabel("N");
      if (FormElementForm.getElementType().equals(FormElementType.ELEMENT_IMAGE) && !Utility.isEmpty(FormElementForm.getUploadFile().getFileName()) ){
        FormElementForm.setFileName(TextUtility.formatFileName(request.getParameter("trueFileName")));
        createRecord(FormElementForm,"image", request);
      }

      // Update From Element.
      FormElementDAObject formElementDAO = new FormElementDAObject(this.
          getSessionContainer(request), this.getConnection(request));
      FormElement formElement = (FormElement) FormElementForm.getFormData();
      formElement = (FormElement) formElementDAO.updateObject(formElement);

      //update record of MTM_FORM_DYNAMICVALUE table begin
      MtmFormDynamicValueDAObject mtmFormDynamicValueDAObject =
        new MtmFormDynamicValueDAObject(this.getSessionContainer(request),this.getConnection(request));
      this.updateMtmDynamicValue(FormElementForm,mtmFormDynamicValueDAObject);
      //update record of MTM_FORM_DYNAMICVALUE table end

      FormElementForm.setFormData(formElement);
      formElement.setLabelPosition(FormElementForm.
          getLabelPosition());
      formElement.setFontType(FormElementForm.getFontType());
      formElement.setFontColor(FormElementForm.getFontColor());
      formElement.setFontSize(TextUtility.parseIntegerObj(
          FormElementForm.getFontSize()));
      String bold = "";
      if (FormElementForm.getFontStyleBold() != null) {
        bold = FormElementForm.getFontStyleBold();
      }
      String underline = "";
      if (FormElementForm.getFontStyleUnderline() != null) {
        underline = FormElementForm.getFontStyleUnderline();
      }
      String italic = "";
      if (FormElementForm.getFontStyleItalic() != null) {
        italic = FormElementForm.getFontStyleItalic();
      }
      formElement.setFontStyle(bold + underline + italic);
      //update for selection type
      if (FormElementType.isSelection(FormElementForm.getElementType())) {
        FormSelectionFieldDAObject FormSelectionFieldDAObject = new
            FormSelectionFieldDAObject(this.getSessionContainer(request),
                                       this.getConnection(request));
        FormSelectionField tmpFormSelectionField = new FormSelectionField();
        FormSelectionField formSelectionField = null;

        try {
          tmpFormSelectionField = (FormSelectionField)
              FormSelectionFieldDAObject.getByElementID(formElement.getID());
          tmpFormSelectionField.setDisplayType(FormElementForm.getDisplayType());
          formSelectionField = (FormSelectionField) FormSelectionFieldDAObject.
              updateObject(tmpFormSelectionField);
        } catch (ApplicationException ae) {
          if (ae.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)) {
            tmpFormSelectionField.setElementID(formElement.getID());
            tmpFormSelectionField.setDisplayType(FormElementForm.getDisplayType());
            formSelectionField = (FormSelectionField)
                FormSelectionFieldDAObject.insertObject(tmpFormSelectionField);
          }
        }

        //set mtm Form data
        FormElementForm.setDisplayType(formSelectionField.getDisplayType());

        //set form selection field option
        FormSelectionFieldOptionDAObject FormSelectionFieldOptionDAObject = new
            FormSelectionFieldOptionDAObject(this.getSessionContainer(request),
                                             this.getConnection(request));
        FormSelectionFieldOption tmpFormSelectionFieldOption = new
            FormSelectionFieldOption();
        FormSelectionFieldOption formSelectionFieldOption = null;

        try {
          tmpFormSelectionFieldOption = (FormSelectionFieldOption)
              FormSelectionFieldOptionDAObject.getBySelectionFieldID(
              formSelectionField.getID());
          FormSelectionFieldOptionDAObject.deleteListBySelectionFieldID(
              formSelectionField.getID());

        } catch (ApplicationException ae) {
          if (ae.getMsgCode().equals(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR)) {

          }
        }
        for (int i = 0; i >= 0 && i < FormElementForm.getOptionList().size(); i++) {
          tmpFormSelectionFieldOption = FormElementForm.getOption(i);
          tmpFormSelectionFieldOption.setSelectionFieldID(formSelectionField.
              getID());
          formSelectionFieldOption = (FormSelectionFieldOption)
              FormSelectionFieldOptionDAObject.insertObject(
              tmpFormSelectionFieldOption);
        }

      }
      if (FormElementForm.getElementType() != null) {
        request.setAttribute("formRecordID", request.getParameter("formRecordID"));
        request.setAttribute("formSectionID", request.getParameter("formSectionID"));
      }

      // released the Form Record.
      if (FormRecord.FORM_STATUS_RELEASED.equals(request.getParameter(
          "formStatus"))) {
        String formRecordID = request.getParameter("formRecordID");
        String updateCount = request.getParameter("formRecordUpdateCount");
        FormRecordDAObject formRecordDAO = new FormRecordDAObject(
            this.getSessionContainer(request), this.getConnection(request));
        formRecordDAO.releaseFormRecord(formRecordID, updateCount);
      }

      setFileName(mapping, form, request, response);
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }

  public void setFileName(ActionMapping mapping, AbstractActionForm form,
                          HttpServletRequest request,
                          HttpServletResponse response)
      throws ApplicationException {
    try {
      MaintFormElementForm FormElementForm = (MaintFormElementForm) form;
      FormElement formElement = (FormElement) FormElementForm.getFormData();
     // formElement = (FormElement) formElementDAO.updateObject(formElement);
      FormElementForm.setFormData(formElement);
      //getfilename
      Integer FormElementID = TextUtility.parseIntegerObj(FormElementForm.getID());
      FormElementForm.setFormData(formElement);
      FormAttachDAObject formAttachDAO = null;
      FormAttach formAttach = null;

      if (FormElementForm.getElementType().equals(FormElementType.ELEMENT_IMAGE)) {
        try {
          formAttachDAO = new FormAttachDAObject(this.getSessionContainer(
              request), this.getConnection(request));
          if (formAttachDAO.getObjectByID(FormElementID) != null) {
            formAttach = (FormAttach) formAttachDAO.getObjectByID(FormElementID);
            FormElementForm.setFileName(formAttach.getFileName());
          }
        } catch (ApplicationException ac) {
        } catch (Exception e) {
        } finally {

        }
      }

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }

  public void deleteRecord(ActionMapping mapping, AbstractActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws ApplicationException {
        MaintFormElementForm formElementForm = (MaintFormElementForm) form;
        String delElementID = "";
        int delElementSeq = 0;
        delElementID = formElementForm.getID();

    //Delete record in MTM_FORM_DYNAMICVALUE table begin
        MtmFormDynamicValueDAObject mtmFormDynamicValueDAObject =
            new MtmFormDynamicValueDAObject(this.getSessionContainer(request),this.getConnection(request));
        deleteMtmDynamicValue(formElementForm,mtmFormDynamicValueDAObject);
    //Delete record in MTM_FORM_DYNAMICVALUE table end

        MtmFormSectionFormElement mtmFormSectionFormElement = new MtmFormSectionFormElement();
        MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO = new MtmFormSectionFormElementDAObject(
                this.getSessionContainer(request), this.getConnection(request));
        FormElementDAObject formElementDAO = new FormElementDAObject(this
                .getSessionContainer(request), this.getConnection(request));

        // Get the seqNo of deleted Element
        mtmFormSectionFormElement = (MtmFormSectionFormElement) mtmFormSectionFormElementDAO
                .getObjectByElementID(new Integer(delElementID));
        delElementSeq = (mtmFormSectionFormElement.getElementSeq()).intValue();
        if (delElementSeq != 0) {
            // Delete section in MTM_FORM_PAGE_FORM_SECTION table
            mtmFormSectionFormElementDAO.deleteObject(mtmFormSectionFormElement);

            // Delete section in FORM_SECTION table
            formElementDAO.deleteObjectByID(new Integer(delElementID));

        }
    }

  //Insert recotd into MTM_FORM_DYNAMICVALUE
  private void insertMtmDynamicValue(MaintFormElementForm formElementForm,
                                 MtmFormDynamicValueDAObject mtmFormDynamicValueDAObject)
                               throws ApplicationException{

    if(formElementForm.getElementType().equals(FormElementType.ELEMENT_TEXT)||
         formElementForm.getElementType().equals(FormElementType.ELEMENT_TEXT_AREA)||
         formElementForm.getElementType().equals(FormElementType.ELEMENT_PASSWORD)||
         FormElementType.isSelection(formElementForm.getElementType())){
          if(!Utility.isEmpty(formElementForm.getSqlField())&&
                 !Utility.isEmpty(formElementForm.getSqlTable())&&
                 !Utility.isEmpty(formElementForm.getSqlWhere())&&
                 !Utility.isEmpty(formElementForm.getConditionID())){
                    StringBuffer sql=new StringBuffer();
                  sql.append(FormConstant.FORM_DB_LOOKUP_SQL_SELECT+FormConstant.FORM_DB_LOOKUP_SQL_SEPARATOR+
                               formElementForm.getSqlField()+FormConstant.FORM_DB_LOOKUP_SQL_SEPARATOR+
                               FormConstant.FORM_DB_LOOKUP_SQL_FROM+FormConstant.FORM_DB_LOOKUP_SQL_SEPARATOR+
                               formElementForm.getSqlTable()+ FormConstant.FORM_DB_LOOKUP_SQL_SEPARATOR+
                                 FormConstant.FORM_DB_LOOKUP_SQL_WHERE+FormConstant.FORM_DB_LOOKUP_SQL_SEPARATOR+
                                 formElementForm.getSqlWhere()+FormConstant.FORM_DB_LOOKUP_SQL_SEPARATOR+
                                 formElementForm.getCompareSymbol()+FormConstant.FORM_DB_LOOKUP_SQL_SEPARATOR+
                                 " ? ");
                log.debug("SQLStatement = "+ sql);
                MtmFormDynamicValue mtmFormDynamicValue = new MtmFormDynamicValue();
            mtmFormDynamicValue.setSqlStatement(sql.toString());
                mtmFormDynamicValue.setConditionElementID(new Integer(formElementForm.getConditionID()));
                mtmFormDynamicValue.setDynamicElementID(new Integer(formElementForm.getID()));
                mtmFormDynamicValue=(MtmFormDynamicValue)mtmFormDynamicValueDAObject.insertObject(mtmFormDynamicValue);
            }
     }
  }

  //Delete record from MTM_FORM_DYNAMICVALUE table
  private void deleteMtmDynamicValue(MaintFormElementForm formElementForm,
                                MtmFormDynamicValueDAObject mtmFormDynamicValueDAObject)
                              throws ApplicationException{

        MtmFormDynamicValue mtmFormDynamicValue = new MtmFormDynamicValue();
        mtmFormDynamicValue.setDynamicElementID(new Integer(formElementForm.getID()));
        mtmFormDynamicValueDAObject.deleteByDynamicElementID(mtmFormDynamicValue);
  }

  //Update record from MTM_FORM_DYNAMICVALUE table
  private void updateMtmDynamicValue(MaintFormElementForm FormElementForm,
                                MtmFormDynamicValueDAObject mtmFormDynamicValueDAObject)
                              throws ApplicationException{
    deleteMtmDynamicValue(FormElementForm,mtmFormDynamicValueDAObject);
    insertMtmDynamicValue(FormElementForm,mtmFormDynamicValueDAObject);
  }

  //Get a record from MTM_FORM_DYNAMICVALUE table
  private void getMtmDynamicValue(FormElement formElement,
                    MtmFormDynamicValueDAObject mtmFormDynamicValueDAObject)
                  throws ApplicationException{

        MtmFormDynamicValue mtmFormDynamicValue = new MtmFormDynamicValue();
        mtmFormDynamicValue.setDynamicElementID(formElement.getID());
        log.debug("DynamicElementID="+mtmFormDynamicValue.getDynamicElementID());
        ArrayList dynamicValues = (ArrayList)mtmFormDynamicValueDAObject.getListByDynamicElementID(mtmFormDynamicValue);
        if(dynamicValues!=null&&dynamicValues.size()>0){
            mtmFormDynamicValue=(MtmFormDynamicValue)dynamicValues.get(0);
          log.debug("DynamicSql="+mtmFormDynamicValue.getConditionElementID()+mtmFormDynamicValue.getDynamicElementID()+mtmFormDynamicValue.getSqlStatement());
        }
        formElement.setDynamicSql(mtmFormDynamicValue);
  }

  public String regexString(String inStr) {
    if (inStr == null) {
      return("");
    }
    String output = inStr;
    output = TextUtility.replaceString(output, "(", "\\(");
    output = TextUtility.replaceString(output, ")", "\\)");
    output = TextUtility.replaceString(output, "[", "\\[");
    output = TextUtility.replaceString(output, "]", "\\]");
    output = TextUtility.replaceString(output, "$", "\\$");
    return(output);
  }
}